package com.tos.second.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tos.second.common.basecontext.BaseContext;
import com.tos.second.common.constant.MessageConstant;
import com.tos.second.common.exception.BaseException;
import com.tos.second.dto.GoodsBuyDto;
import com.tos.second.dto.ShopCartDto;
import com.tos.second.entity.Goods;
import com.tos.second.entity.ShoppingCart;
import com.tos.second.entity.User;
import com.tos.second.mapper.GoodsMapper;
import com.tos.second.mapper.OrdersMapper;
import com.tos.second.mapper.ShoppingCartMapper;
import com.tos.second.mapper.UserMapper;
import com.tos.second.service.GoodsService;
import com.tos.second.service.ShoppingCartService;
import com.tos.second.vo.ShoppingCartGetMyVo;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

@Service
public class ShoopingCartServiceImpl extends ServiceImpl<ShoppingCartMapper, ShoppingCart> implements ShoppingCartService {
    @Autowired
    private GoodsMapper goodsMapper;

    @Autowired
    private ShoppingCartMapper shoppingCartMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private OrdersMapper ordersMapper;

    @Autowired
    private GoodsService goodsService;

    /**
     * 添加商品到购物车
     *
     * @param goodsId
     */
    @Override
    public void add(Long goodsId) {
        //查询当前用户id
        Long currentId = BaseContext.getCurrentId();
        if (currentId == null) {
            throw new BaseException(MessageConstant.USER_NOT_LOGIN);
        }
        //根据商品id查询商品
        Goods goodsById = goodsMapper.getGoodsById(goodsId);
        //判断商品是否为空
        if (goodsById == null) {
            throw new BaseException(MessageConstant.GOODS_NOT_EXIST);
        }
        if (goodsById.getStatus() != 1){
            throw new BaseException(MessageConstant.GOODS_NOT_EXIST);
        }
        //查询商品的创建人
        Long createUserId = goodsById.getCreateUser();

        //判断是否为同一人
        if (currentId.equals(createUserId)) {
            throw new BaseException(MessageConstant.CAN_NOT_BUY_YOURSELF);
        }

        //查询当前用户是否已经添加过该商品
        LambdaQueryWrapper<ShoppingCart> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ShoppingCart::getBuyerId, currentId);
        List<ShoppingCart> shoppingCartList = list(queryWrapper);

        //判断是否已经添加过该商品
        if (!shoppingCartList.isEmpty()) {
            for (ShoppingCart shoppingCart1 : shoppingCartList) {
                if (shoppingCart1.getGoodsId().equals(goodsId)) {
                    throw new BaseException(MessageConstant.GOODS_ALREADY_EXIST);
                }
            }
        }
        checkShoppingCartFull(currentId);
        ShoppingCart shoppingCart = new ShoppingCart();
        //将属性赋值
        shoppingCart.setName(goodsById.getName());
        shoppingCart.setAmount(goodsById.getPrice());
        shoppingCart.setBuyerId(currentId);
        shoppingCart.setImage(goodsById.getImage());
        shoppingCart.setGoodsId(goodsId);
        shoppingCart.setCreateTime(LocalDateTime.now());
        //添加到数据库
        save(shoppingCart);
    }

    private void checkShoppingCartFull(Long currentId) {
        //查询当前用户id
        LambdaQueryWrapper<ShoppingCart> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ShoppingCart::getBuyerId, currentId);
        List<ShoppingCart> list = list(queryWrapper);
        //判断购物车是否已满
        if (list.size() >= 10) {
            throw new BaseException(MessageConstant.SHOPPING_CART_FULL);
        }
    }

    /**
     * 删除购物车
     *
     * @return
     */
    @Override
    public List<ShoppingCartGetMyVo> getAll() {
        //查询当前用户id
        Long currentId = BaseContext.getCurrentId();
        if (currentId == null) {
            throw new BaseException(MessageConstant.USER_NOT_LOGIN);
        }
        //根据用户id查询购物车
        LambdaQueryWrapper<ShoppingCart> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ShoppingCart::getBuyerId, currentId);
        queryWrapper.orderByDesc(ShoppingCart::getCreateTime);

        List<ShoppingCart> list = list(queryWrapper);
        if (list.isEmpty()) {
            return null;
        }
        //根据商品id获得商品具体信息
        List<ShoppingCartGetMyVo> list1 = list.stream().map(shoppingCart -> {
            ShoppingCartGetMyVo shoppingCartGetMyVo = new ShoppingCartGetMyVo();
            //复制属性
            BeanUtils.copyProperties(shoppingCart, shoppingCartGetMyVo);
            //根据商品id获得商品具体信息
            Goods goodsById = goodsMapper.getGoodsById(shoppingCart.getGoodsId());
            //赋值属性
            //根据用户id查询用户
            User userById = userMapper.getById(goodsById.getCreateUser());
            shoppingCartGetMyVo.setSellerName(userById.getName());
            shoppingCartGetMyVo.setStatus(goodsById.getStatus());
            shoppingCartGetMyVo.setCategoryName(goodsById.getCategoryName());
            shoppingCartGetMyVo.setDescription(goodsById.getDescription());
            return shoppingCartGetMyVo;
        }).toList();
        if (list1.isEmpty()) {
            return null;
        }
        return list1;
    }

    @Override
    public void delete(Long id) {
        //查询当前登录用户
        Long currentId = BaseContext.getCurrentId();
        if (currentId == null) {
            throw new BaseException(MessageConstant.USER_NOT_LOGIN);
        }
        //根据购物车id查询购物车
        ShoppingCart shoppingCart = getById(id);
        if (shoppingCart == null){
            throw new BaseException(MessageConstant.SHOPPING_CART_NOT_EXIST);
        }
        Long buyerId = shoppingCart.getBuyerId();
        if (!currentId.equals(buyerId)) {
            throw new BaseException(MessageConstant.CAN_NOT_DELETE_OTHERS_SHOPPING_CART);
        }
        removeById(id);
    }

    @Override
    public void clear() {
        //获得当前登录用户
        Long currentId = BaseContext.getCurrentId();
        if (currentId == null) {
            throw new BaseException(MessageConstant.USER_NOT_LOGIN);
        }


        LambdaQueryWrapper<ShoppingCart> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ShoppingCart::getBuyerId, currentId);
        //清空购物车
        remove(queryWrapper);
    }

    /**
     * 购物车结算
     * @param ids
     */
    @Override
    @Transactional
    public Map<Integer, String> buy(String ids, ShopCartDto shopCartDto) {
        //将ids转为集合
        List<Long> idList = Arrays.asList(ids.split(",")).stream().map(Long::parseLong).toList();
        //获得当前登录用户
        Long currentId = BaseContext.getCurrentId();
        if (currentId == null) {
            throw new BaseException(MessageConstant.USER_NOT_LOGIN);
        }
        //根据购物车id查询购物车
        List<ShoppingCart> shoppingCarts = listByIds(idList);

        // 创建Map来存储订单号，key为序号，value为订单号
        Map<Integer, String> orderNumbersMap = new LinkedHashMap<>();

        int index = 1; // 序号从1开始
        for (ShoppingCart shoppingCart : shoppingCarts) {
            //判断是否为自己的购物车
            Long buyerId = shoppingCart.getBuyerId();
            if (!currentId.equals(buyerId)) {
                throw new BaseException(MessageConstant.CAN_NOT_BUY_OTHERS_SHOPPING_CART);
            }
            GoodsBuyDto goodsBuyDto = new GoodsBuyDto();
            goodsBuyDto.setDescription("无");
            goodsBuyDto.setNumber(shopCartDto.getNumber());
            goodsBuyDto.setStatus(shopCartDto.getStatus());

            // 执行购买操作并收集订单号
            String orderNumber = goodsService.buy(shoppingCart.getGoodsId(), goodsBuyDto);
            orderNumbersMap.put(index++, orderNumber);
        }
        //如果status等于1或2
        if (shopCartDto.getStatus() == 1 || shopCartDto.getStatus() == 2) {
            GoodsBuyDto goodsBuyDto = new GoodsBuyDto();
            goodsBuyDto.setDescription("无");
            goodsBuyDto.setNumber(shopCartDto.getNumber());
            goodsBuyDto.setStatus(shopCartDto.getStatus());
            goodsService.buy(null, goodsBuyDto);
            //removeByIds(idList);
        }
        return orderNumbersMap;

        //removeByIds(idList);
    }
}
